<?php
/**
 * 全局公共控制器类
 */
namespace app\admin\controller;

use think\exception\ValidateException;
use app\BaseController;

class Common extends BaseController
{
    protected $validate;           //全局验证
    protected $localModel;         //本控制器下模型
    protected $validateType;       //验证情景

    /**
     * 单表信息全局新增|编辑
     * @return \think\response\Json
     */
    public function save(){
        $dataArr = $this->request->request('info/a', []);
        $id = $this->request->post('id', 0);

        if($msg = $this->checkData($dataArr, $this->validateType))  return json(['result'=>'fail', 'title'=>$msg]);

        $res = $this->localModel->saveDataInfo($dataArr, $id);

        if(!$res)  return json(['result'=>'fail', 'title'=>'操作失败！']);

        $this->logsData = ['cid'=>$id ? $id : $res, 'action'=>$id ? 'edit' : 'add'];
        return json(['result'=>'success', 'title'=>'恭喜您操作成功！', 'url'=>(string)url($this->request->controller().'/index')]);
    }

    /**
     * 单表信息全局删除
     * @return \think\response\Json
     */
    public function del(){
        $id = $this->request->post('id', 0);

        if(!$id)  return json(array('result'=>'fail', 'title'=>'参数不能为空！'));

        //删除角色
        $delRes = $this->localModel->del($id);
        if(!$delRes)  return json(array('result'=>'fail', 'title'=>'操作失败！'));
        $this->logsData =  ['cid'=>$id, 'action'=>'del'];

        return json(array('result'=>'success'));
    }

    /**
     * 全局审核
     * 参数ID为当前内容ID,examine_num表示当前为第几次审核
     * @return \think\response\Json
     */
    public function examine(){
        $examine_status = $this->request->post('examine_status', 1);
        $examine_num = $num = $this->request->post('examine_num', 1);
        $data = [
            'scope'          => $this->request->post('scope', 1),
            'reason'         => $this->request->post('reason', ''),
            'examine_status' => $examine_status == 10 ? $examine_status : ($examine_num >= $this->request->examineNum ? 9 : ++$examine_num)
        ];

        $id = $this->request->post('id', 0);
        if(!$id)  return json(['result'=>'fail', 'title'=>'参数ID不存在！']);

        $res = $this->localModel->saveDataInfo($data, $id);

        if(!$res)  return json(['result'=>'fail', 'title'=>'审核失败！']);

        $this->logsData = ['cid'=>$id, 'action'=>$num.'_examine', 'msg'=>$this->request->post('reason', '')];
        return json(array('result'=>'success'));
    }

    /**
     * 全局验证
     * @param $data                待验证数组
     * @param string $scene        验证识别标识
     * @return array|string
     */
    protected function checkData($data, $scene = ''){
        try {
            validate($this->validate)->scene($scene)->check($data);
        } catch (ValidateException $e) {
            return $e->getError();
        }
    }

    //测试服务
    public function testServiceDi(){
        $this->app->sqlLog->setData();
    }

    protected function writeLog(){
        event('WriteLog', $this->logsData);
    }

}
